package com.lanlian.commonlib;

import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
import android.os.Handler;
import android.util.DisplayMetrics;

import com.lanlian.utillib.PreferencesUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @author xiaobo.hu
 * @version v1.0
 * @date on 2018/08/03
 * @email 834366578@qq.com
 * @describe Application基类
 */
public class BaseApplication extends Application {

    private static BaseApplication instance;
    private Set<Activity> allActivities;

    public static synchronized BaseApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        setScreenInfo();
    }

    /**
     * 获取屏幕信息并保存
     */
    private void setScreenInfo() {
        int statusBarHeight = 0;
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = resources.getDimensionPixelSize(resourceId);
        }
        if (statusBarHeight > 0) {
            PreferencesUtils.putInt(this, "statusBarHeight", statusBarHeight);
        }
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        int screenWidth = displayMetrics.widthPixels;
        if (screenWidth > 0) {
            PreferencesUtils.putInt(this, "screenWidth", screenWidth);
        }
        int screenHeight = displayMetrics.heightPixels;
        if (screenHeight > 0) {
            PreferencesUtils.putInt(this, "screenHeight", screenHeight);
        }
        float screenDensity = displayMetrics.density;
        if (screenDensity > 0) {
            PreferencesUtils.putFloat(this, "screenDensity", screenDensity);
        }
    }

    /**
     * 添加activity
     */
    public void addActivity(Activity act) {
        if (allActivities == null) {
            allActivities = new HashSet<>();
        }
        allActivities.add(act);
    }

    /**
     * 移除activity
     */
    public void removeActivity(Activity act) {
        if (allActivities != null) {
            allActivities.remove(act);
        }
    }

    /**
     * 退出app
     */
    public void exitApp() {
        if (allActivities != null) {
            synchronized (allActivities) {
                for (Activity act : allActivities) {
                    act.finish();
                }
            }
        }
        System.exit(0);
    }

    public void exitAppDelayed() {
        if (allActivities != null) {
            synchronized (allActivities) {
                for (Activity act : allActivities) {
                    act.finish();
                }
            }
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                System.exit(0);
            }
        }, 1000);
    }

    /**
     * 这还有一系列的第三方SDK的初始化
     */

}
